import { Injectable } from '@angular/core';
import { isString } from '../../util';
import { StoreService } from './store.service';


@Injectable({
  providedIn: 'root'
})
export class MenuService<B, S> {
  // 系统菜单的树形结构
  private menuTree: Menu[];
  // 系统菜单的列表结构
  private menuList: Menu[];
  // 有对应页面的菜单集合，键为url，值为菜单对象
  private pageMenu: Map<string, Menu>;

  constructor(private storeService: StoreService<B, S>) { }


  // 初始化菜单信息，参数为菜单原始数据，如果为空从localStorage中读取
  init(menuTree?: Menu[]) {
    if (!menuTree) {
      menuTree = this.storeService.getItem(<any>'Menu') || [];
    } else {
      this.storeService.setItem(<any>'Menu', menuTree);
    }

    this.menuTree = menuTree;

    this.menuList = [];
    this.pageMenu = new Map<string, Menu>();
    this.initPageMenuAndMenuList(menuTree);
  }

  getMenuTree(): Menu[] {
    if (!this.pageMenu) {
      this.init();
    }
    return this.menuTree;
  }

  getMenuList(): Menu[] {
    if (!this.pageMenu) {
      this.init();
    }
    return this.menuList;
  }

  getPageMenu(): Map<string, Menu> {
    if (!this.pageMenu) {
      this.init();
    }
    return this.pageMenu;
  }

  private initPageMenuAndMenuList(menuTree) {
    menuTree.forEach((menu) => {
      if (!menu) {
        return;
      }

      this.menuList.push(menu);
      if (isString(menu.url) && menu.url) {
        menu.url = menu.url.startsWith('/') ? menu.url : '/' + menu.url;
        this.pageMenu.set(menu.url, menu);
      }

      if (Array.isArray(menu.childList)) {
        this.initPageMenuAndMenuList(menu.childList);
      }
    });
  }


}

export interface Menu {
  name: string;
  menuType?: number;
  url?: string;
  acl?: string;
  icon?: string;
  childList?: Menu[];
}
